<!--文件上传-->
<template>
  <ele-modal
    width="460px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    title="上传文件"
    limit="30"
    @update:visible="updateVisible"
  >
    <el-upload
      ref="upload"
      :disabled="loading == true?true:false"
      :file-list="fileList"
      :on-change="onUpload"
      :auto-upload="false"
      :accept="accept"
      class="upload-demo"
      drag
      :action="ossUrl"
      multiple>

      <!--      <i :class="loading == true ? 'el-icon-loading' : 'el-icon-upload'"></i>-->
      <i class="el-icon-upload" v-show="loading == false"></i>
      <el-image v-show="loading == true" style="width: 67px;    margin: 40px 0 16px;
    line-height: 50px;" :src="require('/src/assets/loading.gif')"></el-image>

      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传{{accept.replace(/,/g,' / ')}}文件，且不超过200M</div>
    </el-upload>
    <template v-slot:footer>
    <el-button
      size="small"
      @click="updateVisible(false)"
    >
      取消上传
    </el-button>
    <el-button
      :loading="loading"
      size="small"
      type="primary"
      @click.stop="selectVideo()"
    >
      开始上传
    </el-button>
    </template>
  </ele-modal>
</template>

<script>
  // import OSS from '/src/utils/js/aliyun.js';
  import axios from 'axios'
  // import {getToken} from "../../../../../utils/token-util";
  import {getToken} from "../../../../../utils/token-util";
  import { addUserFile, userOssList,userOssSignature,registerMedia} from '@/api/creatCenter/material';
    export default {
        name: "file-upload",
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 父级 id
        parentId: Number,
        accept:String
      },
      data() {
        return {
          ossUrl:localStorage.getItem('ossUrl')?localStorage.getItem('ossUrl'):'', //上传图片action
          loading:false,
          fileList:[],
          data:{},
          isFile:false,
          // 用于判断，是否上传到最后一个
          isNum:0
        };
      },
      created() {
      },
      methods:{
        async selectVideo(){
          this.isNum=0
          console.log("this.fileList.length",this.fileList.length)
          if(this.fileList.length < 1) {
            console.log("请选择文件后提交")
            this.$message.error('请选择文件后提交');
            return
          }
          let isLt = true
          for(let i=0;i<this.fileList.length;i++){
            // 判断是否小于2mb
            if(this.fileList[i].size / 1024 / 1024 > 200){
              isLt=false
            }
          }
          if (!isLt) {
            for(let i=0;i<this.fileList.length;i++){
              // 判断是否小于2mb
              if(this.fileList[i].size / 1024 / 1024 > 200){
                this.fileList.splice(i,1)
              }
            }
            this.$message.error("请上传小于200MB文件");
            return
          }
          this.isFile=true
          this.$refs.upload.submit();  // 图片上传进度(修改隐藏)
          this.data = await userOssSignature()
          console.log('this.fileList.length',this.fileList.length)

          this.loading=true
          for(let i=0;i<this.fileList.length;i++){
            console.log('this.fileList.length22222222',this.fileList.length)
            let file = this.fileList[i].raw
            console.log(file)
            let filename=file.name;
            let markIndex=(filename).lastIndexOf('.');
            let suffix=filename.substring(markIndex)
            let date=new Date().getTime();
            // 构建请求参数
            let param = new FormData()
            param.append("key", this.data.dir + date+suffix)
            param.append("policy", this.data.policy)
            param.append("OSSAccessKeyId", this.data.accessId)
            param.append("success_action_status", '200')
            // param.append("callback",  this.data.callback)     //回调（not)
            param.append("signature", this.data.signature)
            param.append("file", file, file.name)
            param.append('success_action_status', '200')
            let config = {
              headers: {
                'Access-Control-Allow-Origin': '*',
                'x-oss-callback-Authorization': getToken()
              }
            }
            console.log("suffix",suffix)
            axios.post(this.data.host, param, config).then(res => {
              if(res.status==200){
                // 修改
                // this.$refs.upload.submit();  // 图片上传进度
                console.log('this.data.host',this.data.host+'/'+date+suffix)
                let url=this.data.host+'/'+date+suffix;
                let type=file.type;
                console.log('进入上传file.type=====',file.type)
                // this.fileList=[]
                this.registerMedias(url,type);
              }
              else{
                this.loading=false
                this.$message.error('上传失败');
              }

            }).catch(err => {
              console.log(err)
            })
          }
        },
      //  未使用
      async httpRequest(paramcs){
          console.log("paramcs",paramcs)
          this.data = await userOssSignature()
          this.loading=true
          for(let i=0;i<this.fileList.length;i++) {
            let file = this.fileList[i].raw
            console.log(file)
            let filename = file.name;
            let markIndex = (filename).lastIndexOf('.');
            let suffix = filename.substring(markIndex)
            let date = new Date().getTime();
            // 构建请求参数
            let param = new FormData()
            param.append("key", this.data.dir + date + suffix)
            param.append("policy", this.data.policy)
            param.append("OSSAccessKeyId", this.data.accessId)
            param.append("success_action_status", '200')
            // param.append("callback",  this.data.callback)     //回调（not)
            param.append("signature", this.data.signature)
            param.append("file", file, file.name)
            param.append('success_action_status', '200')
            let config = {
              headers: {
                'Access-Control-Allow-Origin': '*',
                'x-oss-callback-Authorization': getToken()
              },
              onUploadProgress: (progressEvent) => {
                console.log('progressEvent',progressEvent)
                console.log('progressEvent.loaded / progressEvent.total',progressEvent.loaded / progressEvent.total)
                let num = progressEvent.loaded / progressEvent.total  | 0;
                // let num = progressEvent.loaded / progressEvent.total * 100 | 0;
                let paramcs = new FormData()
                paramcs.onProgress({percent: num})     //进度条
              }
            }
            console.log("suffix", suffix)
            axios.post(this.data.host, param, config).then(res => {
              if (res.status == 200) {
                // 修改
                // this.$refs.upload.submit();  // 图片上传进度
                console.log('this.data.host', this.data.host + '/' + date + suffix)
                let url = this.data.host + '/' + date + suffix;
                let type = file.type;
                console.log('进入上传file.type=====', file.type)
                // this.fileList=[]
                this.registerMedias(url, type);
              } else {
                this.loading = false
                this.$message.error('上传失败');
              }

            }).catch(err => {
              console.log(err)
            })
          }
        },


        registerMedias(url,type) {
          registerMedia({
            mediaUrl:url,//上传阿里云生成的地址
            mediaType:type,//文件类型
            username:this.$store.state.user.info.username,
            folderId:this.parentId

          })
            .then((data) => {
              this.isNum++
              console.log("this.isNum",this.isNum,'this.fileList.length',this.fileList.length)
              // setTimeout(()=>{
              if(this.fileList.length == this.isNum){  // (修改隐藏)
                console.log("进入上传成功=======")
                this.$message.success('上传成功');
                this.loading=false
                //关闭弹窗
                this.updateVisible(false);
                console.log("进入上传成功关闭=======")

                // 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
                this.$refs['upload'].clearFiles()
                this.onDone();
              }
              // },500)
            })
            .catch((e) => {
              this.loading=false
              this.$message.error(e.message);
            });
        },
        /* 更新 visible */
        updateVisible(value) {
          // 除了上传时，为了避免重复调用push_fileList,所以在上传时标识isFile为true，return_push
          this.isFile=false
          this.fileList=[]
          console.log('this.accept',this.accept)
          this.$emit('update:visible', value);
        },

        /* 上传 */
        onUpload(file) {
          console.log("this.isFile",this.isFile)
          // 修改
          if(this.isFile==true){
            return
          }
          this.fileList.push(file)
          console.log('this.fileList',this.fileList)
        },
        //暂未使用
        beforeUpload(file) {
          console.log("进入判断图片file===", file);
          var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
          let isLt = file.size / 1024 / 1024 < 200; // 判断是否小于2mb
          console.log("testmsg===", testmsg);
          // .jpg,.jpeg,.png,.pdf,.PDF
          const extension1 = testmsg === "jpg";
          const extension2 = testmsg === "jpeg";
          const extension3 = testmsg === "png";

          // const isLt2M = file.size / 1024 / 1024 < 10
          // if (!extension1 && !extension2 && !extension3) {
          //   this.$message.error("请上传jpg 、png、jpeg 类型图片!");
          //   return false;
          // } else
            if (!isLt) {
              this.fileList=[]
            this.$message.error("请上传小于200MB图片");
            return false;
          } else {
            return true;
          }
        },
        onRemove(e,fileList){
          this.fileList=fileList;
          console.log("移除图片钩子",e,'this.fileList',this.fileList)
        },
        uploadFile(file){
          uploadFile(file)
        .then((data) => {
            addUserFile({
              name: data.name,
              isDirectory: 0,
              parentId: this.parentId,
              path: data.path,
              length: data.length,
              contentType: data.contentType
            })
              .then(() => {
                this.$message.success('上传成功');
                this.onDone();
              })
              .catch((e) => {
                this.$message.error(e.message);
              });
          })
            .catch((e) => {
              this.$message.error(e.message);
            });
          return false;
          // return true;
        },
        /* 完成刷新列表数据 */
        onDone() {
          this.$emit('done');
        },
      }
    }
</script>

<style scoped>
  /deep/ .el-upload-dragger{
    width: 420px !important;
  }

  /* 上传组件 —— 下load（加载中）图标样式 */
  /deep/ .el-upload-dragger .el-icon-loading{
    font-size: 67px;
    color: var(--color-text-placeholder);
    margin: 40px 0 16px;
    line-height: 50px;
  }
</style>
